package com.hbnu.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class TouristAuthenticationProvider implements AuthenticationProvider {
    private final TouristDetailServiceImpl  touristDetailService;
    private final PasswordEncoder  passwordEncoder;

    public TouristAuthenticationProvider(TouristDetailServiceImpl touristDetailService, PasswordEncoder passwordEncoder) {
        this.touristDetailService = touristDetailService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        UserDetails tourist = touristDetailService.loadUserByUsername(username);
        if (!passwordEncoder.matches(password, tourist.getPassword())) {
            log.info("密码错误");
            throw new BadCredentialsException("密码错误");
        } else if (tourist.isEnabled()) {
            log.info("用户已注销");
            throw new DisabledException("用户已注销");
        }
        return new UsernamePasswordAuthenticationToken(
                tourist,
                null, // 认证后清除凭证
                tourist.getAuthorities()
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
